class AdminController < ApplicationController
  before_filter :admin?
  def backuppage
    file_dir = "#{RAILS_ROOT}/public/backupfiles/documents"
    db_dir = "#{RAILS_ROOT}/public/backupfiles/databases"
    @file_list = Dir.entries(file_dir)
    @db_list = Dir.entries(db_dir)
    render :action=>"backuppage", :layout=>"main"
  end

  def backup
    require 'zip/zip'
    file_path = "#{RAILS_ROOT}/public/materials"
    zipfile_name = "#{RAILS_ROOT}/public/backupfiles/documents/#{Time.now.strftime('%Y_%m_%d_%H_%M_%S')}.zip"
    begin
      File.delete(zipfile_name)
    rescue
    end
    attachs = Material.find(:all, :conditions=>["zip_flag=?",'N'])
    Zip::ZipFile.open(zipfile_name, Zip::ZipFile::CREATE) do |zipfile|
      attachs.each do |a|
#        begin
          zipfile.add(a.id.to_s, file_path + '/' + a.filename)
          a.zip_flag = 'Y'
          a.save
#        rescue
#        end
      end
    end

    db_path = "#{RAILS_ROOT}/public/backupfiles/databases"
    cmd = "mysqldump -uchaiyo -p45664566 dloc_elearning|gzip > #{db_path}/#{Time.now.strftime('%Y_%m_%d_%H_%M_%S')}.sql.gz"
#    puts cmd
    system(cmd)
    redirect_to :action=>"backuppage"
  end

  def deletebackup1
    file_dir = "#{RAILS_ROOT}/public/backupfiles/documents"
    begin
      File.delete(file_dir+"/"+params[:filename])
    rescue
    end
    redirect_to :action=>"backuppage"
  end

  def deletebackup3
    db_dir = "#{RAILS_ROOT}/public/backupfiles/databases"
    begin
      File.delete(db_dir+"/"+params[:filename])
    rescue
    end
    redirect_to :action=>"backuppage"
  end

  def restoredb
    db_path = "#{RAILS_ROOT}/public/backupfiles/databases"
    cmd = "gzip -d < #{db_path}/#{params[:filename]} | mysql -uchaiyo -p45664566 dloc_elearning"
    system(cmd)
    redirect_to :action=>"backuppage"
  end

  def uploadbackup
    filename = "#{RAILS_ROOT}/public/backupfiles/databases/#{params['pfile'].original_filename.gsub(/[^a-zA-Z0-9.]/, '_')}"
    begin
      File.delete(filename)
    rescue
    end
    File.open(filename, "wb") do |f|
			f.write(params['pfile'].read)
		end
    redirect_to :action=>"backuppage"
  end

end
